// src/stores/employee.ts
import { defineStore } from 'pinia';
import axios from '@/plugins/axios';

// 员工数据接口
export interface Employee {
  id: number;
  name: string;
  phone: string;
  departmentId: number;
  departmentName?: string;
  createTime: string;
}

// 员工表单字段配置
export const employeeFields = [
  { key: 'name', label: '姓名', type: 'text', placeholder: '请输入员工姓名', maxLength: 20 },
  { key: 'phone', label: '电话', type: 'text', placeholder: '请输入员工电话', maxLength: 11 },
  {
    key: 'departmentId',
    label: '部门',
    type: 'select',
    placeholder: '请选择部门',
    options: [], // 动态填充部门数据
  },
];

export const useEmployeeStore = defineStore('employee', {
  state: () => ({
    employees: [] as Employee[],
  }),
  actions: {
    // 获取员工列表
    async fetchEmployees() {
      try {
        const response = await axios.get('/employees');
        if (response.data.code === 200) {
          this.employees = response.data.data;
          return this.employees;
        }
        throw new Error(response.data.message || '获取员工失败');
      } catch (error) {
        throw new Error('获取员工失败');
      }
    },
    // 创建员工
    async createEmployee(data: { name: string; phone: string; departmentId: number }) {
      const response = await axios.post('/employees', data);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '创建员工失败');
    },
    // 更新员工
    async updateEmployee(data: Employee) {
      const response = await axios.put('/employees', data);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '更新员工失败');
    },
    // 删除员工
    async deleteEmployee(id: number) {
      const response = await axios.delete(`/employees/${id}`);
      if (response.data.code === 200) {
        return response.data.data;
      }
      throw new Error(response.data.message || '删除员工失败');
    },
  },
});